<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane label="班级分布" name="class">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <div slot="header" class="clearfix">
                <span>各班级学生人数分布（饼图）</span>
              </div>
              <div id="studentPieChart" style="height: 400px;" />
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <div slot="header" class="clearfix">
                <span>各班级学生人数分布（柱状图）</span>
              </div>
              <div id="studentBarChart" style="height: 400px;" />
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="学生属性" name="attributes">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <div slot="header" class="clearfix">
                <span>学生性别比例</span>
              </div>
              <div id="genderChart" style="height: 400px;" />
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <div slot="header" class="clearfix">
                <span>学生状态分布</span>
              </div>
              <div id="statusChart" style="height: 400px;" />
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="时间趋势" name="time">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-card shadow="hover" class="chart-card">
              <div slot="header" class="clearfix">
                <span>学生加入时间趋势</span>
              </div>
              <div id="joinDateChart" style="height: 400px;" />
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getAllClassStudentCounts } from '@/api/class'
import { getStudentGenderStats, getStudentStatusStats, getStudentJoinDateStats } from '@/api/statistics'

export default {
  data() {
    return {
      activeTab: 'class',
      pieChart: null,
      barChart: null,
      genderChart: null,
      statusChart: null,
      joinDateChart: null,
      chartInstances: []
    }
  },
  watch: {
    activeTab(newVal) {
      this.$nextTick(() => {
        this.resizeCharts()

        // 根据当前激活的标签页加载相应的图表数据
        if (newVal === 'class' && (!this.pieChart || !this.barChart)) {
          this.initClassCharts()
        } else if (newVal === 'attributes' && (!this.genderChart || !this.statusChart)) {
          this.initAttributeCharts()
        } else if (newVal === 'time' && !this.joinDateChart) {
          this.initTimeCharts()
        }
      })
    }
  },
  mounted() {
    this.initCharts()
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts)
    this.disposeCharts()
  },
  methods: {
    // 初始化所有图表
    initCharts() {
      // 初始化当前激活标签页的图表
      if (this.activeTab === 'class') {
        this.initClassCharts()
      } else if (this.activeTab === 'attributes') {
        this.initAttributeCharts()
      } else if (this.activeTab === 'time') {
        this.initTimeCharts()
      }
    },

    // 初始化班级分布图表
    initClassCharts() {
      this.pieChart = echarts.init(document.getElementById('studentPieChart'))
      this.barChart = echarts.init(document.getElementById('studentBarChart'))
      this.chartInstances.push(this.pieChart, this.barChart)

      this.loadClassData()
    },

    // 初始化学生属性图表
    initAttributeCharts() {
      this.genderChart = echarts.init(document.getElementById('genderChart'))
      this.statusChart = echarts.init(document.getElementById('statusChart'))
      this.chartInstances.push(this.genderChart, this.statusChart)

      this.loadGenderData()
      this.loadStatusData()
    },

    // 初始化时间趋势图表
    initTimeCharts() {
      this.joinDateChart = echarts.init(document.getElementById('joinDateChart'))
      this.chartInstances.push(this.joinDateChart)

      this.loadJoinDateData()
    },

    // 加载班级数据
    async loadClassData() {
      try {
        const res = await getAllClassStudentCounts()
        if (res.data.code === 1) {
          const classData = res.data.data

          // 通用数据
          const classNames = classData.map(item => item.className)
          const studentCounts = classData.map(item => item.studentCount)

          // 饼图数据
          const pieData = classData.map(item => ({
            name: item.className,
            value: item.studentCount
          }))

          // 饼图配置
          this.pieChart.setOption({
            title: {
              text: '各班级学生人数分布',
              left: 'center'
            },
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              data: classNames
            },
            series: [
              {
                name: '学生人数',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: pieData,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          })

          // 柱状图配置
          this.barChart.setOption({
            title: {
              text: '各班级学生人数分布',
              left: 'center'
            },
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              type: 'category',
              data: classNames,
              axisLabel: {
                interval: 0,
                rotate: 30
              }
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: '学生人数',
                type: 'bar',
                data: studentCounts,
                itemStyle: {
                  color: function(params) {
                    const colorList = ['#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622']
                    return colorList[params.dataIndex % colorList.length]
                  }
                }
              }
            ]
          })
        } else {
          this.$message.error('获取班级人数失败：' + res.data.msg)
        }
      } catch (error) {
        console.error(error)
        this.$message.error('请求出错')
      }
    },

    // 加载性别数据
    loadGenderData() {
      getStudentGenderStats()
        .then(response => {
          const genderData = response.data.data || {
            labels: ['男', '女'],
            values: [60, 40]
          }

          this.genderChart.setOption({
            title: {
              text: '学生性别比例',
              left: 'center'
            },
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              data: genderData.labels
            },
            series: [
              {
                name: '性别比例',
                type: 'pie',
                radius: ['50%', '70%'], // 环形图
                avoidLabelOverlap: false,
                label: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: '30',
                    fontWeight: 'bold'
                  }
                },
                labelLine: {
                  show: false
                },
                data: genderData.labels.map((label, index) => ({
                  name: label,
                  value: genderData.values[index]
                }))
              }
            ]
          })
        })
        .catch(error => {
          console.error('获取性别统计失败：', error)
          // 使用模拟数据
          const mockData = {
            labels: ['男', '女'],
            values: [60, 40]
          }

          this.genderChart.setOption({
            title: {
              text: '学生性别比例',
              left: 'center'
            },
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              data: mockData.labels
            },
            series: [
              {
                name: '性别比例',
                type: 'pie',
                radius: ['50%', '70%'], // 环形图
                avoidLabelOverlap: false,
                label: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: '30',
                    fontWeight: 'bold'
                  }
                },
                labelLine: {
                  show: false
                },
                data: mockData.labels.map((label, index) => ({
                  name: label,
                  value: mockData.values[index]
                }))
              }
            ]
          })
        })
    },

    // 加载状态数据
    loadStatusData() {
      getStudentStatusStats()
        .then(response => {
          const statusData = response.data.data || {
            labels: ['在读', '已离开'],
            values: [85, 15]
          }

          this.statusChart.setOption({
            title: {
              text: '学生状态分布',
              left: 'center'
            },
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              data: statusData.labels
            },
            series: [
              {
                name: '学生状态',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: [
                  {
                    name: statusData.labels[0],
                    value: statusData.values[0],
                    itemStyle: { color: '#91cc75' }
                  },
                  {
                    name: statusData.labels[1],
                    value: statusData.values[1],
                    itemStyle: { color: '#ee6666' }
                  }
                ],
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          })
        })
        .catch(error => {
          console.error('获取状态统计失败：', error)
          // 使用模拟数据
          const mockData = {
            labels: ['在读', '已离开'],
            values: [85, 15]
          }

          this.statusChart.setOption({
            title: {
              text: '学生状态分布',
              left: 'center'
            },
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              data: mockData.labels
            },
            series: [
              {
                name: '学生状态',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: [
                  {
                    name: mockData.labels[0],
                    value: mockData.values[0],
                    itemStyle: { color: '#91cc75' }
                  },
                  {
                    name: mockData.labels[1],
                    value: mockData.values[1],
                    itemStyle: { color: '#ee6666' }
                  }
                ],
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          })
        })
    },

    // 加载加入时间数据
    loadJoinDateData() {
      getStudentJoinDateStats()
        .then(response => {
          const joinData = response.data.data || {
            months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            counts: [5, 8, 12, 6, 3, 15, 20, 25, 10, 5, 3, 8]
          }

          this.joinDateChart.setOption({
            title: {
              text: '学生加入时间趋势',
              left: 'center'
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            legend: {
              data: ['加入人数']
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: joinData.months
            },
            yAxis: {
              type: 'value',
              name: '人数'
            },
            series: [
              {
                name: '加入人数',
                type: 'line',
                smooth: true,
                data: joinData.counts,
                markPoint: {
                  data: [
                    { type: 'max', name: '最大值' },
                    { type: 'min', name: '最小值' }
                  ]
                },
                markLine: {
                  data: [
                    { type: 'average', name: '平均值' }
                  ]
                },
                areaStyle: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                      offset: 0, color: 'rgba(58,77,233,0.8)'
                    }, {
                      offset: 1, color: 'rgba(58,77,233,0.1)'
                    }]
                  }
                }
              }
            ]
          })
        })
        .catch(error => {
          console.error('获取加入时间统计失败：', error)
          // 使用模拟数据
          const mockData = {
            months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            counts: [5, 8, 12, 6, 3, 15, 20, 25, 10, 5, 3, 8]
          }

          this.joinDateChart.setOption({
            title: {
              text: '学生加入时间趋势',
              left: 'center'
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            legend: {
              data: ['加入人数']
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: mockData.months
            },
            yAxis: {
              type: 'value',
              name: '人数'
            },
            series: [
              {
                name: '加入人数',
                type: 'line',
                smooth: true,
                data: mockData.counts,
                markPoint: {
                  data: [
                    { type: 'max', name: '最大值' },
                    { type: 'min', name: '最小值' }
                  ]
                },
                markLine: {
                  data: [
                    { type: 'average', name: '平均值' }
                  ]
                },
                areaStyle: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                      offset: 0, color: 'rgba(58,77,233,0.8)'
                    }, {
                      offset: 1, color: 'rgba(58,77,233,0.1)'
                    }]
                  }
                }
              }
            ]
          })
        })
    },

    // 调整图表大小
    resizeCharts() {
      this.chartInstances.forEach(chart => {
        if (chart) chart.resize()
      })
    },

    // 销毁图表
    disposeCharts() {
      this.chartInstances.forEach(chart => {
        if (chart) chart.dispose()
      })
      this.chartInstances = []
    }
  }
}
</script>

<style scoped>
.chart-card {
  margin-bottom: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>
